package com.manager.user.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.manager.common.result.Result;
import com.manager.model.dto.SellerDto;
import com.manager.model.dto.UpdateDto;
import com.manager.model.model.Update;
import com.manager.model.model.User;
import com.manager.user.mapper.UpdateMapper;
import com.manager.user.mapper.UserUserMapper;
import com.manager.user.service.UserUserService;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import static com.manager.common.result.ResultCodeEnum.OLD_PASSWORD_ERROR;


@Service
public class UserUserServiceImpl extends ServiceImpl<UserUserMapper, User> implements UserUserService {

    @Resource
    private UpdateMapper updateMapper;

    //通过id获取用户信息
    @Override
    public Result<User> getUserById(String id) {
        User user = this.getById(id);
        return Result.ok(user);
    }
    //分页查询销售
    @Override
    public Result<Page> pageSellers(int page, int pageSize) {
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);
        //构造条件构造器
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.eq(User::getRole,1);
        //添加排序条件
        wrapper.orderByAsc(User::getId);
        //执行查询
        this.page(pageInfo,wrapper);
        return Result.ok(pageInfo);
    }
    //添加销售
    @Override
    public Result<String> addSeller(User user) {
        String account = user.getAccount();
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User one = this.getOne(wrapper);
        if (one != null){
            return Result.fail("账号已存在");
        }
        user.setRole(1);
        this.save(user);
        return Result.ok("添加成功");
    }
    //修改销售
    @Override
    public Result<String> modifySellerInfo(User user) {
        this.updateById(user);
        return Result.ok("修改成功");
    }
    //批量禁用销售
    @Override
    public Result<String> disableSellers(List<String> ids) {
        for (String id : ids) {
            User user = this.getById(id);
            user.setStatus(0);
            this.updateById(user);
        }
        return Result.ok("禁用成功");
    }

    //导出跟进内容
    @Override
    public void exportUpdateContent(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("跟进内容", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            List<Update> updateList = updateMapper.selectList(null);
            List<UpdateDto> updateDtoList = new ArrayList<>(updateList.size());
            for(Update update : updateList) {
                UpdateDto updateDto = new UpdateDto();
                Integer sellerId = update.getUpdatePerson();
                User seller = this.getById(sellerId);
                String sellerName = seller.getName();
                updateDto.setUpdatePerson(sellerName);
                BeanUtils.copyProperties(update,updateDto);
                updateDtoList.add(updateDto);
            }
            EasyExcel.write(response.getOutputStream(), UpdateDto.class).sheet("跟进内容").doWrite(updateDtoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //修改基本资料
    @Override
    public Result modifyInfo(String account, String name) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User user = this.getOne(wrapper);
        if (user == null){
            return Result.fail("用户不存在");
        }
        user.setName(name);
        this.updateById(user);
        return Result.ok(true);
    }

    //修改密码
    @Override
    public Result modifyPassword(String account, String oldPassword, String newPassword) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount,account);
        User user = this.getOne(wrapper);
        if (user == null){
            return Result.fail("用户不存在");
        }
        String old = user.getPassword();
        if (!old.equals(oldPassword)){
            return Result.fail(OLD_PASSWORD_ERROR);
        }
        user.setPassword(newPassword);
        this.updateById(user);
        return Result.ok("修改成功");
    }
    //批量启用销售
    @Override
    public Result<String> ableSellers(List<String> ids) {
        for (String id : ids) {
            User user = this.getById(id);
            user.setStatus(1);
            this.updateById(user);
        }
        return Result.ok("启用成功");
    }
    //导出销售信息
    @Override
    public void export(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("销售信息", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getRole,1);
            List<User> list = this.list(wrapper);
            ArrayList<SellerDto> sellerDtoList = new ArrayList<>(list.size());
            for (User user : list) {
                Integer status = user.getStatus();
                SellerDto sellerDto = new SellerDto();
                BeanUtils.copyProperties(user,sellerDto);
                if (status == 0){
                    sellerDto.setStatus("禁用中");
                }else {
                    sellerDto.setStatus("启用中");
                }
                sellerDtoList.add(sellerDto);
            }
            EasyExcel.write(response.getOutputStream(), SellerDto.class).sheet("销售信息").doWrite(sellerDtoList);
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
